import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Article } from '@/interfaces/article';
import EditorToolbar from '@/components/common/EditorToolbar';
import MarkdownEditor from '@/components/common/MarkdownEditor';
import PreviewPane from '@/components/common/PreviewPane';
import ArticleMetaEditor from '@/components/common/ArticleMetaEditor';
import SaveStatus from '@/components/common/SaveStatus';

const Editor: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const isEditMode = Boolean(id);
  
  const [article, setArticle] = useState<Article>({
    id: id || '',
    title: '',
    content: '',
    excerpt: '',
    author: 'Current User',
    publishDate: new Date().toISOString(),
    lastModified: new Date().toISOString(),
    tags: [],
    category: '',
    readTime: 0,
    status: 'draft',
    coverImage: ''
  });

  const [isPreviewMode, setIsPreviewMode] = useState(false);
  const [saveStatus, setSaveStatus] = useState<'saved' | 'saving' | 'error'>('saved');
  const [showMetaEditor, setShowMetaEditor] = useState(false);

  // Auto-save functionality
  useEffect(() => {
    const autoSave = setTimeout(() => {
      if (article.title || article.content) {
        handleSave();
      }
    }, 2000);

    return () => clearTimeout(autoSave);
  }, [article.title, article.content]);

  // Load article if editing
  useEffect(() => {
    if (isEditMode && id) {
      // Simulate loading article
      setSaveStatus('saving');
      setTimeout(() => {
        setArticle(prev => ({
          ...prev,
          title: 'Sample Article Title',
          content: '# Sample Article\n\nThis is a sample article content...',
          excerpt: 'This is a sample excerpt',
          tags: ['React', 'TypeScript'],
          category: 'Development'
        }));
        setSaveStatus('saved');
      }, 1000);
    }
  }, [isEditMode, id]);

  const handleSave = async () => {
    setSaveStatus('saving');
    
    try {
      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // Update read time based on content
      const wordCount = article.content.split(/\s+/).filter(word => word.length > 0).length;
      const readTime = Math.ceil(wordCount / 200); // Average reading speed
      
      setArticle(prev => ({
        ...prev,
        readTime,
        lastModified: new Date().toISOString()
      }));
      
      setSaveStatus('saved');
    } catch (error) {
      setSaveStatus('error');
    }
  };

  const handlePublish = async () => {
    if (!article.title || !article.content) {
      alert('Please fill in title and content before publishing');
      return;
    }

    setSaveStatus('saving');
    
    try {
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      setArticle(prev => ({
        ...prev,
        status: 'published',
        publishDate: new Date().toISOString()
      }));
      
      setSaveStatus('saved');
      navigate(`/article/${article.id || '1'}`);
    } catch (error) {
      setSaveStatus('error');
    }
  };

  const handleDiscard = () => {
    if (window.confirm('Are you sure you want to discard your changes?')) {
      navigate('/');
    }
  };

  return (
    <div className="min-h-screen bg-white dark:bg-ios-gray-900">
      {/* Header */}
      <header className="sticky top-0 z-50 bg-white/80 dark:bg-ios-gray-900/80 backdrop-blur-apple border-b border-ios-gray-200 dark:border-ios-gray-700">
        <div className="max-w-7xl mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-4">
              <button
                onClick={() => navigate('/')}
                className="text-ios-gray-600 dark:text-ios-gray-400 hover:text-ios-blue transition-colors"
              >
                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
              
              <h1 className="text-xl font-semibold text-ios-gray-900 dark:text-white">
                {isEditMode ? 'Edit Article' : 'New Article'}
              </h1>
              
              <SaveStatus status={saveStatus} />
            </div>

            <div className="flex items-center space-x-3">
              <button
                onClick={() => setShowMetaEditor(true)}
                className="px-4 py-2 text-ios-gray-600 dark:text-ios-gray-400 hover:text-ios-blue transition-colors"
              >
                Settings
              </button>
              
              <button
                onClick={handleDiscard}
                className="px-4 py-2 text-ios-red hover:text-ios-red/80 transition-colors"
              >
                Discard
              </button>
              
              <button
                onClick={handleSave}
                className="px-4 py-2 bg-ios-gray-100 dark:bg-ios-gray-700 text-ios-gray-700 dark:text-ios-gray-300 rounded-apple-md hover:bg-ios-gray-200 dark:hover:bg-ios-gray-600 transition-colors"
              >
                Save Draft
              </button>
              
              <button
                onClick={handlePublish}
                className="px-4 py-2 bg-ios-blue text-white rounded-apple-md hover:bg-ios-blue/90 transition-colors"
              >
                Publish
              </button>
            </div>
          </div>
        </div>
      </header>

      {/* Editor Toolbar */}
      <EditorToolbar
        isPreviewMode={isPreviewMode}
        onTogglePreview={() => setIsPreviewMode(!isPreviewMode)}
        onBold={(text) => setArticle(prev => ({ ...prev, content: prev.content + text }))}
        onItalic={(text) => setArticle(prev => ({ ...prev, content: prev.content + text }))}
        onLink={(text) => setArticle(prev => ({ ...prev, content: prev.content + text }))}
        onImage={(text) => setArticle(prev => ({ ...prev, content: prev.content + text }))}
        onCode={(text) => setArticle(prev => ({ ...prev, content: prev.content + text }))}
      />

      {/* Main Editor */}
      <main className="max-w-7xl mx-auto px-4 py-6">
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 h-[calc(100vh-200px)]">
          {/* Editor Pane */}
          <div className={`${isPreviewMode ? 'hidden lg:block' : ''}`}>
            <MarkdownEditor
              title={article.title}
              content={article.content}
              onTitleChange={(title) => setArticle(prev => ({ ...prev, title }))}
              onContentChange={(content) => setArticle(prev => ({ ...prev, content }))}
              placeholder="Write your article..."
            />
          </div>

          {/* Preview Pane */}
          <div className={`${!isPreviewMode ? 'hidden lg:block' : ''}`}>
            <PreviewPane
              title={article.title}
              content={article.content}
              article={article}
            />
          </div>
        </div>
      </main>

      {/* Meta Editor Modal */}
      {showMetaEditor && (
        <ArticleMetaEditor
          article={article}
          onSave={(updatedArticle) => {
            setArticle(updatedArticle);
            setShowMetaEditor(false);
          }}
          onCancel={() => setShowMetaEditor(false)}
        />
      )}
    </div>
  );
};

export default Editor;